package com.woke.fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.bean.BaseResponse;
import com.bean.FootItem;
import com.bean.UserHeadColumn;
import com.bilibili.boxing.Boxing;
import com.bilibili.boxing.model.config.BoxingConfig;
import com.bilibili.boxing.model.config.BoxingCropOption;
import com.bilibili.boxing.model.entity.BaseMedia;
import com.bilibili.boxing.model.entity.impl.ImageMedia;
import com.bilibili.boxing.utils.BoxingFileHelper;
import com.bilibili.boxing.utils.ImageCompressor;
import com.bilibili.boxing_impl.ui.BoxingActivity;
import com.example.woke.PuFaMerchantsInActivity;
import com.http.HttpMethods;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.woke.adapter.FootItemViewBinder;
import com.woke.adapter.OnItemClickListener;
import com.woke.adapter.RealNameColumnViewProvider;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.zhongcai.online.R;

import net.bither.util.NativeUtil;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import pub.devrel.easypermissions.EasyPermissions;

import static android.app.Activity.RESULT_OK;
import static me.drakeet.multitype.MultiTypeAsserts.assertAllRegistered;

/**
 * Created by Administrator on 2017/5/8 0008.
 */

public class PuFaIdCardAuthFragment extends BaseFrag implements EasyPermissions.PermissionCallbacks {

    private ProgressDialog mProgressDialog;
    private XRecyclerView xRecyclerView;
    private MultiTypeAdapter mMulitypeAdapter;
    private Items mItems;
    private Toast mToast;

    private static final int MAX_IMAGE_SIZE = 200 * 1024;
    private static final int REQUEST_CODE_FRONT = 8;  //正面照
    private static final int REQUEST_CODE_REVERSE = 2; //反面照
    private static final int REQUEST_CODE_WHOLE = 6;   //全身照(手持身份证照)
    private int tempRequestCode = -1;
    private File tempFrontFile, tempReverseFile, tempWholeFile;
    private MyApp myApp;

    @Override
    public int getMenuId() {
        return 0;
    }

    @Override
    public void OnNavigationClickListener(View v) {
        if (getActivity() != null) {
            getActivity().finish();
        }
    }

    @Override
    public boolean OnMenuItemClickListener(MenuItem item) {
        return false;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myApp = MyApp.getInstance();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_base_list, container, false);
        initToolbar(rootView, true);
        setTitle(getResources().getString(R.string.in_the_list));
        initRecyclerView(rootView);
        initLoadingProgress();
        initLayoutManagerAndProgressStyle();
        initData();
        initMulitypeAdapter();
        initLoadingProgress();
        return rootView;
    }

    private void initRecyclerView(View rootView) {
        xRecyclerView = (XRecyclerView) rootView.findViewById(R.id.xRecyclerView);
    }

    private void initLoadingProgress() {
        if (getContext() != null) {
            mProgressDialog = new ProgressDialog(getContext());
            mProgressDialog.setMessage(getResources().getString(R.string.hint_update_in));
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        }
    }

    private void initData() {

        mItems = new Items();
        mItems.add(new UserHeadColumn("", getResources().getString(R.string.ic_card_front), String.class));
        mItems.add(new UserHeadColumn("", getResources().getString(R.string.ic_card_reverse), String.class));

        mItems.add(new FootItem(getResources().getString(R.string.sure_space)));

    }

    private void initMulitypeAdapter() {

        mMulitypeAdapter = new MultiTypeAdapter() {
            @Override
            public void onAttachedToRecyclerView(RecyclerView recyclerView) {
                super.onAttachedToRecyclerView(recyclerView);
                RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                if (manager instanceof GridLayoutManager) {
                    final GridLayoutManager gridManager = ((GridLayoutManager) manager);
                    gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                        @Override
                        public int getSpanSize(int position) {
                            if (position == 0 || position >= mItems.size())
                                return 2;
                            return 1;
                        }
                    });
                }
            }
        };
        mMulitypeAdapter.applyGlobalMultiTypePool();

        mMulitypeAdapter.register(UserHeadColumn.class, new RealNameColumnViewProvider(mItemClickListener));
        mMulitypeAdapter.register(FootItem.class, new FootItemViewBinder(mItemClickListener));


        mMulitypeAdapter.setItems(mItems);
//		mMulitypeAdapter.notifyDataSetChanged ();
        if (mItems.size() > 0) {
            assertAllRegistered(mMulitypeAdapter, mItems);//执行这句话时,必须保证 Items.size()>0
        }
        xRecyclerView.setAdapter(mMulitypeAdapter);
    }

    public void initLayoutManagerAndProgressStyle() {
        xRecyclerView.setPadding(0, getResources().getDimensionPixelSize(R.dimen.activity_vertical_margin), 0, 0);
        xRecyclerView.setLoadingMoreEnabled(false);
        xRecyclerView.setPullRefreshEnabled(false);
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);

        xRecyclerView.setLayoutManager(layoutManager);
        xRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
    }

    private OnItemClickListener mItemClickListener = new OnItemClickListener() {


        @Override
        public void OnItemClick(View view, int position) {

        }

        @Override
        public void OnItemClick(View view, Object object, int position) {
            if (object instanceof UserHeadColumn) {
                UserHeadColumn column = (UserHeadColumn) object;
                if (TextUtils.isEmpty(column.getColumnName())) return;
                if (getResources().getString(R.string.ic_card_front)
                        .equals(column.getColumnName())) {
                    //正面照
                    choosePic(REQUEST_CODE_FRONT);
                } else if (getResources().getString(R.string.ic_card_reverse)
                        .equals(column.getColumnName())) {
                    //反面照
                    choosePic(REQUEST_CODE_REVERSE);
                }
//                else if (getResources().getString(R.string.ic_card_whole)
//                        .equals(column.getColumnName())) {
//                    //手持身份证照
//                    choosePic(REQUEST_CODE_WHOLE);
//                }
                showToast(column.getColumnName());
            } else if (object instanceof FootItem) {
                //提交
                commit();
            }
        }
    };

    private void showToast(String msg) {
        if (getContext() != null) {
            if (mToast == null) {
                mToast = Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT);
            }
            mToast.setText(msg);
            mToast.show();
        }
    }

    private void choosePic(int requestCode) {
        tempRequestCode = requestCode;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            methodRequiresTwoPermission();
        } else {
            requestCode(requestCode);
        }
    }

    private void commit() {

        if (tempFrontFile == null) {
            showToast(getResources().getString(R.string.hint_id_card_front_null));

            return;
        }
        if (tempReverseFile == null) {
            showToast(getResources().getString(R.string.hint_id_card_reverse_null));
            return;
        }

        Datas_load load = myApp.getDatas_load();
        if (load != null) {
            String userId = load.getId();
            if (!TextUtils.isEmpty(userId) && userId.matches("[0-9]*")) {
                mProgressDialog.show();
                HttpMethods.getInstance()
                        .picSec(mCommitObserver, Integer.parseInt(userId), tempFrontFile, tempReverseFile);

            } else {
                showToast("您还未登录");
            }
        }

    }


    private Observer<BaseResponse> mCommitObserver = new Observer<BaseResponse>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(BaseResponse value) {

            if (value != null) {
                if (value.resultSuccess()) {
                    showToast(value.getInfo());
                    xRecyclerView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (getActivity() != null) {
                                startActivity(new Intent(getActivity(), PuFaMerchantsInActivity.class));
                                getActivity().finish();
                            }
                        }
                    }, 1000);

                } else {
                    showToast(value.getInfo());
                }
            } else {
                showToast(getResources().getString(R.string.hint_error_server));
            }
        }

        @Override
        public void onError(Throwable e) {
            if (e != null) {
                showToast(e.getMessage());
            }
        }

        @Override
        public void onComplete() {
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
            }
        }
    };

    /**
     * --------------------权限管理start---------------------------------
     */

    private static final int REQUEST_READ_EXTERNAL_STORAGE = 8;

    private void methodRequiresTwoPermission() {
        if (getContext() == null) return;
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            if (tempRequestCode != -1) {
                requestCode(tempRequestCode);
            }
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "应用需要读写权限",
                    REQUEST_READ_EXTERNAL_STORAGE, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        Log.e("Permission", "onPermissionsGranted");
        if (requestCode == REQUEST_READ_EXTERNAL_STORAGE) {
            if (tempRequestCode != -1) {
                requestCode(tempRequestCode);
            }
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Log.e("Permission", "onPermissionsDenied");
        if (requestCode == REQUEST_READ_EXTERNAL_STORAGE) {
            new AlertDialog.Builder(getContext()).setMessage("请在<权限管理>里打开读写权限")
                    .setPositiveButton("前往", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            intent.setData(Uri.fromParts("package", getContext().getPackageName(), null));
                            startActivity(intent);
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create()
                    .show();
        }
    }

	/* --------------------权限管理end-----------------------------------*/


    /**
     * 单选并裁剪
     *
     * @param requestCode
     */
    private void requestCode(int requestCode) {
        if (getContext() == null) return;
        String cachePath = BoxingFileHelper.getCacheDir(getContext());
        if (TextUtils.isEmpty(cachePath)) {
            showToast(getResources().getString(R.string.boxing_storage_deny));
            return;
        }
        Uri destUri = new Uri.Builder()
                .scheme("file")
                .appendPath(cachePath)
                .appendPath(String.format(Locale.US, "%s.jpg", System.currentTimeMillis()))
                .build();
        BoxingConfig singleCropImgConfig = new BoxingConfig(BoxingConfig.Mode.SINGLE_IMG).withCropOption(new BoxingCropOption(destUri));
        Boxing.of(singleCropImgConfig)
                .withIntent(getContext(), BoxingActivity.class)
                .start(this, requestCode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_FRONT:
                case REQUEST_CODE_REVERSE:
                case REQUEST_CODE_WHOLE:
                    final ArrayList<BaseMedia> medias = Boxing.getResult(data);
                    BaseMedia baseMedia = medias.get(0);
                    if (!(baseMedia instanceof ImageMedia)) {
                        return;
                    }
                    final ImageMedia imageMedia = (ImageMedia) baseMedia;
                    // the compress task may need time
                    if (imageMedia.compress(new ImageCompressor(getContext()), MAX_IMAGE_SIZE)) {
                        imageMedia.removeExif();
                        handleImageFile(requestCode, imageMedia.getThumbnailPath());
                    }
                    break;

            }
        }
    }

    private void handleImageFile(int requestCode, String imagePath) {
        if (TextUtils.isEmpty(imagePath)) return;
        String cachePath = BoxingFileHelper.getCacheDir(getContext());
        if (TextUtils.isEmpty(cachePath)) {
            showToast(getResources().getString(R.string.boxing_storage_deny));

            return;
        }
        File file = new File(cachePath, String.format(Locale.US, "%s.jpg", System.currentTimeMillis()));
        try {
            NativeUtil.mixCompress(BitmapFactory.decodeFile(imagePath), file.getAbsolutePath());
            Log.e("---", new FileInputStream(file).available() + "");
            switch (requestCode) {
                case REQUEST_CODE_FRONT:
                    tempFrontFile = file;
                    mItems.set(0, new UserHeadColumn(file.getAbsolutePath(), getResources().getString(R.string.ic_card_front), String.class));
                    break;
                case REQUEST_CODE_REVERSE:
                    tempReverseFile = file;
                    mItems.set(1, new UserHeadColumn(file.getAbsolutePath(), getResources().getString(R.string.ic_card_reverse), String.class));
                    break;
                case REQUEST_CODE_WHOLE:
                    tempWholeFile = file;
                    mItems.set(2, new UserHeadColumn(file.getAbsolutePath(), getResources().getString(R.string.ic_card_whole), String.class));
                    break;

            }
            if (mMulitypeAdapter != null) {
                mMulitypeAdapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
        }
    }
}
